#include "apdu_digest_manager.h"

#include "../../mk_lib/mk_utility.h"

#include <string.h>
#include <memory.h>
#include <stdlib.h>

apdu_digest_manager::apdu_digest_manager( void )
{

}

apdu_digest_manager::~apdu_digest_manager( void )
{

}

apdu * apdu_digest_manager::create_apdu_digest_init(int hash_algo, unsigned char * sm2_pub_key_blob, int pub_key_blob_len, 
													unsigned char * user_id, int id_len, int display)
{
	apdu * newApdu = NULL;
	
	if(sm2_pub_key_blob == NULL || pub_key_blob_len == 0)
	{
		newApdu = new apdu(SC_APDU_CASE_1, 0x80, 0xB4, display, hash_algo, "DigestInit");
	}
	else
	{
		newApdu = new apdu(SC_APDU_CASE_3_EXT, 0x80, 0xB4, display, hash_algo, "DigestInit");
		
		unsigned char data[4096] = {0};
		memcpy(data, sm2_pub_key_blob, pub_key_blob_len);

		int pos = pub_key_blob_len;
		mk_utility::fill_buff_with_dword_value_be(id_len, data + pos);
		pos += 4;

		memcpy(data + pos, user_id, id_len);
		pos += id_len;

		newApdu->set_lc_data(data, pos);
	}

	return newApdu;
}

apdu * apdu_digest_manager::create_apdu_digest( unsigned char * input, int input_len )
{
	apdu * newApdu = new apdu(SC_APDU_CASE_4_EXT, 0x80, 0xB6, 0, 0, "Digest");

	newApdu->set_lc_data(input, input_len);

	return newApdu;
}

apdu * apdu_digest_manager::create_apdu_digest_update( unsigned char * input, int input_len, int display)
{
	apdu * newApdu = new apdu(SC_APDU_CASE_3_EXT, 0x80, 0xB8, display, 0, "DigestUpdate");

	newApdu->set_lc_data(input, input_len);

	return newApdu;
}


apdu * apdu_digest_manager::create_apdu_digest_final( unsigned char * input, int input_len )
{
	apdu * newApdu = NULL;
	if(input_len > 0)
	{
		newApdu = new apdu(SC_APDU_CASE_4_EXT, 0x80, 0xBA, 0, 0, "DigestFinal");
		newApdu->set_lc_data(input, input_len);
	}
	else
	{
		newApdu = new apdu(SC_APDU_CASE_2_EXT, 0x80, 0xBA, 0, 0, "DigestFinal");
	}

	return newApdu;
}

apdu * apdu_digest_manager::create_apdu_digest_file( int app_id, int offset, int read_len, char * file_name )
{
	apdu * newApdu = new apdu(SC_APDU_CASE_4_EXT, 0xC0, 0x90, 0x00, 0x00, "DigestFileUpdate");

	int pos = 0;
	unsigned char data[128] = {0};
	mk_utility::fill_buff_with_word_value_be(app_id, data);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(offset, data + pos);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(read_len, data + pos);
	pos += 2;

	int name_len = strlen(file_name);
	mk_utility::fill_buff_with_word_value_be(name_len, data + pos);
	pos += 2;

	memcpy(data + pos, file_name, name_len);
	pos += name_len;


	newApdu->set_lc_data(data, pos);
	newApdu->set_le(read_len);

	return newApdu;	
}

